/******************************************************************************\
    Semaphore.hpp contains a class of windows semaphore.
    Copyright (C) 2008  Victor Vinogradov (fly3333@gmail.com)

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
\******************************************************************************/

#ifndef __SEMAPHORE_HPP
#define __SEMAPHORE_HPP

#include "Handle.hpp"

class cSemaphore : public cObject< cSubHandle >
{
public:
	bool Create( LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, LONG lInitialCount, LONG lMaximumCount, LPCTSTR lpName )
	{
		HANDLE handle = CreateSemaphore( lpSemaphoreAttributes, lInitialCount, lMaximumCount, lpName );
		if( handle == NULL )
			return false;
		cSubHandle *sub_handle;
		try
		{
			sub_handle = new cSubHandle( handle );
		}
		catch( ... )
		{
			return false;
		}
		SwitchToSubObject( sub_handle );
		return true;
	}
	void Destroy()
	{
		SwitchToSubObject( NULL );
	}
	operator HANDLE() const
	{
		if( GetSubObject() == NULL )
			return NULL;
		return GetSubObject()->Handle();
	}
	bool Release( LONG lReleaseCount, LPLONG lpPreviousCount )
	{
		if( GetSubObject() == NULL )
			return false;
		return ::ReleaseSemaphore( GetSubObject()->Handle(), lReleaseCount, lpPreviousCount ) != FALSE;
	}
};

#endif
